const Koa = require('./koa-2.5.1/lib/application');//https://chenshenhai.github.io/koa2-note/note/route/koa-router.html
const app = new Koa();
const render = require('koa-ejs');
var json = require('koa-json');
const logger = require('koa-logger')
const cors = require('koa-cors');
const path = require('path');
const static  = require('koa-static');
const router = require('./router/index')
var body = require('koa-better-body')
var onerror = require('Koa-onerror');
const compress = require('koa-compress');
const convert = require('koa-convert');
const MongooseStore = require('koa-session-mongoose');
const session = require('koa-session');//https://segmentfault.com/a/1190000013039187

const connection=require('./mongodb/mongodb').connect();
app.keys = ['some secret hurr'];

const log=require('./middleware/log');
const upload=require('./middleware/upload');
app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
  ctx.set('X-Response-Time', `${ms}ms`);
});
app.use(session({
    store: new MongooseStore({
      collection: 'appSessions',
      expires: 86400, // 1 day is the default
      name: 'AppSession'
    })
}, app));


onerror(app);
app.use(cors({
    origin: function (req) {
      //console.log(req.header);
        // if (req.url === '/login') {
           //return 'http://127.0.0.1:3333'
        // }
        return 'http://localhost:3333';
        return 'http://127.0.0.1:3010';
        return '*'; // 这样就能只允许 http://localhost:8080 这个域名的请求了
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))
app.use(compress({
    threshold: 2048,
    flush: require('zlib').Z_SYNC_FLUSH
}))
app.use(json());
app.use(body({
    fields: 'body'
}));
app.use(upload(['picture','file']));
app.use(async (ctx,next)=>{
	try{
		await next();//throw 抛出错误 
	}catch(err){//接受throw 抛出的
		ctx.response.status = err.statusCode || err.status || ctx.status || 500;
	    // ctx.response.body = {
	    //   message: err.message
        // };
        await ctx.render('error', {
            message: err.message,
            errorCode:ctx.response.status
        });
	    ctx.app.emit('error', err, ctx);//如果try捕获错误就不会执行error 需要手动触 发
	}
})

app.use(static(__dirname + '/public'));
app.use(static(__dirname + '/upload'));

render(app, {
    root: path.join(__dirname, 'views'),
    layout: 'template',
    viewExt: 'html',
    cache: false,
    debug: true
});

//app.use(logger());

//;
router(app);



app.on('error', (err, ctx) => {
    console.error('server error', err, `${ctx.method} ${ctx.url} `)
});
// // 设置端口号。
// app.port = parseInt(process.env.PORT || '3000');

// // koa2服务器启动。
// app.listen(app.port, () => {
//   console.log(`http://127.0.0.1:${app.port} 已经启动(时间：${new Date().toLocaleString()})...`);
// });
  
module.exports = app;